package com.test.config;

import lombok.extern.slf4j.Slf4j;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.internal.Util;
import okhttp3.logging.HttpLoggingInterceptor;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import javax.net.ssl.*;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

@Slf4j
@Configuration
public class OkHttpConfig {

    @Bean
    public X509TrustManager x509TrustManager() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
    }

    @Bean
    public SSLSocketFactory sslSocketFactory() {
//        try {
//            //信任任何链接
//            SSLContext sslContext = SSLContext.getInstance("TLS");
//            sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());
//            return sslContext.getSocketFactory();
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        } catch (KeyManagementException e) {
//            e.printStackTrace();
//        }
        String[] certs = new String[]{"1530210831", "1511682811"};

        SSLContextBuilder sslContextBuilder = SSLContexts.custom();
        try {
            for (int i = 0; i < certs.length; i++) {
                ClassPathResource resource = new ClassPathResource("certs/" + certs[i] + ".p12");
                InputStream fis = resource.getInputStream();
                KeyStore ks = KeyStore.getInstance("pkcs12");
                ks.load(fis, certs[i].toCharArray());
                Util.closeQuietly(fis);
                sslContextBuilder.loadKeyMaterial(ks, certs[i].toCharArray());
            }
            SSLContext sslContext = sslContextBuilder.build();
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            log.error("customSSLSocketFactory.error", e);
        }
        return null;
    }

    /**
     * Create a new connection pool with tuning parameters appropriate for a single-user application.
     * The tuning parameters in this pool are subject to change in future OkHttp releases. Currently
     */
    @Bean
    public ConnectionPool pool() {
        return new ConnectionPool(200, 5, TimeUnit.MINUTES);
    }

    @Bean
    public HttpLoggingInterceptor logInterceptor() {
        HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(HttpLoggingInterceptor.Logger.DEFAULT);
        logInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        return logInterceptor;
    }

    @Bean
    public HostnameVerifier hostnameVerifier() {
        return (s, sslSession) -> true;
    }

    @Bean
    public OkHttpClient okHttpClient() {
        return new OkHttpClient.Builder()
                .sslSocketFactory(sslSocketFactory(), x509TrustManager())
                .addInterceptor(logInterceptor())
                .hostnameVerifier(hostnameVerifier())
                .retryOnConnectionFailure(false)//是否开启缓存
                .connectionPool(pool())//连接池
                .connectTimeout(10L, TimeUnit.SECONDS)
                .readTimeout(10L, TimeUnit.SECONDS)
                .build();
    }
}
